<?php

require_once "process_file.php";

function php_file_condition($fi)
{
    return strtolower($fi->getExtension()) == 'php';
}

function strip_php_comment($str)
{
    $newStr = '';

    $commentTokens = array(T_COMMENT);

    if (defined('T_DOC_COMMENT')) {
        $commentTokens[] = T_DOC_COMMENT;
    }

    $tokens = token_get_all($str);
    $eol = detect_eol($str);

    foreach ($tokens as $token) {
        if (is_array($token)) {
            if (in_array($token[0], $commentTokens)) {
                // 包含[Discuz!]和[UCenter]的是版权注释，不去掉
                if (str_contains($token[1], '[Discuz!]') || str_contains($token[1], '[UCenter]')) {
                    $newStr .= $token[1];
                }
                // 单行注释去掉后，后面加回车，避免把两行弄到一起
                if (substr($token[1], 0, 2) != "/*") {
                    $newStr .= $eol;
                }
                continue;
            }
            $token = $token[1];
        }
        $newStr .= $token;
    }
    return $newStr;
}

function strip_one_php_file($from_file, $to_file)
{
    $should_strip = true;

    // config文件中的注释不去掉
    if (ends_with($from_file, 'config_global_default.php')) $should_strip = false;
    if (ends_with($from_file, 'config_ucenter_default.php')) $should_strip = false;

    $buffer = file_get_contents($from_file);
    if ($should_strip) $buffer = strip_php_comment($buffer);

    mkdir_of_file($to_file);
    file_put_contents($to_file, $buffer);
}

function strip_all_php_files($from_path, $to_path)
{
    logging\info("processing PHP files");
    process_all_files_with_condition($from_path, $to_path, 'php_file_condition', 'strip_one_php_file');
}

?>